<template>
  <div class="page-container">
    <div class="page-content">
      <!-- 数据统计卡片 -->
      <div class="stats-cards">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ totalPosts }}</div>
                <div class="stat-label">帖子总数</div>
                <div class="stat-icon total">
                  <FileTextOutlined />
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">+{{ todayNewPosts }}</div>
                <div class="stat-label">今日新增</div>
                <div class="stat-icon today">
                  <PlusCircleOutlined />
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ pendingPosts }}</div>
                <div class="stat-label">待审核</div>
                <div class="stat-icon pending">
                  <ClockCircleOutlined />
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ formatViewCount(totalViews) }}</div>
                <div class="stat-label">总浏览量</div>
                <div class="stat-icon views">
                  <EyeOutlined />
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 图表展示区域 -->
      <div class="charts-section">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-card title="帖子发布趋势（堆叠图）" class="chart-card">
              <div ref="publishTrendChart" class="chart-container"></div>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card title="帖子状态统计" class="chart-card">
              <div ref="statusDistributionChart" class="chart-container"></div>
            </a-card>
          </a-col>
        </a-row>
        <a-row :gutter="16" style="margin-top: 16px">
          <a-col :span="12">
            <a-card title="学校发帖排行" class="chart-card">
              <div ref="schoolRankChart" class="chart-container"></div>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card title="互动数据概览" class="chart-card">
              <div ref="interactionChart" class="chart-container"></div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 帖子管理表格 -->
      <a-card>
        <!-- 搜索表单 -->
        <div class="search-form">
          <a-form layout="inline" :model="searchForm">
            <a-form-item label="帖子标题">
              <a-input
                v-model:value="searchForm.title"
                placeholder="请输入帖子标题"
                style="width: 200px"
                allow-clear
                @pressEnter="handleSearch"
              />
            </a-form-item>
            <a-form-item label="帖子状态">
              <a-select
                v-model:value="searchForm.postStatus"
                placeholder="请选择帖子状态"
                style="width: 150px"
                allow-clear
              >
                <a-select-option value="published">已发布</a-select-option>
                <a-select-option value="pending">审核中</a-select-option>
                <a-select-option value="hidden">已隐藏</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="是否置顶">
              <a-select
                v-model:value="searchForm.isPinned"
                placeholder="请选择置顶状态"
                style="width: 130px"
                allow-clear
              >
                <a-select-option :value="1">已置顶</a-select-option>
                <a-select-option :value="0">未置顶</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="所属学校">
              <a-select
                v-model:value="searchForm.schoolId"
                placeholder="请选择学校"
                style="width: 200px"
                show-search
                allow-clear
                :filter-option="false"
                @search="handleSchoolSearch"
              >
                <a-select-option v-for="school in schoolList" :key="school.id" :value="school.id">
                  {{ school.schoolName }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleSearch">
                <SearchOutlined />
                查询
              </a-button>
              <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
              <PermissionButton permission="circle:post:add" style="margin-left: 8px">
                <a-button type="primary" @click="handleAdd">
                  <PlusOutlined />
                  新增帖子
                </a-button>
              </PermissionButton>
            </a-form-item>
          </a-form>
        </div>

        <!-- 表格 -->
        <a-table
          :columns="columns"
          :data-source="tableData"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          :scroll="{ x: 1500 }"
          @change="handleTableChange"
        >
          <!-- 帖子内容 -->
          <template #content="{ record }">
            <div class="content-preview">
              {{
                record.content && record.content.length > 50
                  ? record.content.substring(0, 50) + '...'
                  : record.content || '暂无内容'
              }}
            </div>
          </template>

          <!-- 发布者信息 -->
          <template #publisher="{ record }">
            <div class="publisher-info">
              <div class="publisher-name">
                {{ record.userNickName || '未知用户' }}
              </div>
              <div class="publisher-meta">
                <a-tag v-if="record.isAnonymous === 1" color="orange" size="small">
                  <EyeInvisibleOutlined />
                  匿名
                </a-tag>
                <a-tag v-else color="blue" size="small">
                  <UserOutlined />
                  实名
                </a-tag>
              </div>
            </div>
          </template>

          <!-- 学校信息 -->
          <template #school="{ record }">
            <div class="school-info">
              <a-tag v-if="record.schoolName" color="green">
                <BankOutlined />
                {{ record.schoolName }}
              </a-tag>
              <a-tag v-else color="purple">
                <GlobalOutlined />
                全局帖子
              </a-tag>
            </div>
          </template>

          <!-- 帖子状态 -->
          <template #postStatus="{ record }">
            <a-tag :color="getStatusColor(record.postStatus)">
              {{ getStatusText(record.postStatus) }}
            </a-tag>
          </template>

          <!-- 置顶状态 -->
          <template #pinStatus="{ record }">
            <div v-if="record.isPinned === 1" class="pin-status">
              <a-popover title="置顶信息" trigger="click" placement="topLeft">
                <template #content>
                  <div class="pin-detail">
                    <p v-if="record.pinExpireTime">
                      <strong>过期时间：</strong><br />
                      {{ formatDateTime(record.pinExpireTime) }}
                    </p>
                    <p v-else>
                      <strong>永久置顶</strong>
                    </p>
                    <div style="margin-top: 12px">
                      <PermissionButton permission="circle:post:pin">
                        <a-button type="primary" size="small" danger @click="handleUnpin(record)">
                          取消置顶
                        </a-button>
                      </PermissionButton>
                    </div>
                  </div>
                </template>
                <a-tag color="red" style="cursor: pointer">
                  <PushpinOutlined />
                  已置顶
                </a-tag>
              </a-popover>
            </div>
            <span v-else class="text-muted">普通</span>
          </template>

          <!-- 统计信息 -->
          <template #stats="{ record }">
            <div class="stats-info">
              <div class="stat-item">
                <EyeOutlined />
                <span>{{ record.viewCount || 0 }}</span>
              </div>
              <div class="stat-item">
                <LikeOutlined />
                <span>{{ record.likeCount || 0 }}</span>
              </div>
              <div class="stat-item">
                <MessageOutlined />
                <span>{{ record.commentCount || 0 }}</span>
              </div>
            </div>
          </template>

          <!-- 操作列 -->
          <template #action="{ record }">
            <div class="action-buttons">
              <PermissionButton permission="circle:post:detail">
                <a-button
                  type="link"
                  size="small"
                  @click="handleViewDetail(record)"
                  class="action-btn"
                >
                  <EyeOutlined />
                </a-button>
              </PermissionButton>

              <PermissionButton permission="circle:post:edit">
                <a-button type="link" size="small" @click="handleEdit(record)" class="action-btn">
                  <EditOutlined />
                </a-button>
              </PermissionButton>

              <PermissionButton permission="circle:post:audit">
                <a-button
                  v-if="record.postStatus === 'pending'"
                  type="link"
                  size="small"
                  @click="handleAudit(record, 'published')"
                  class="action-btn audit-btn"
                >
                  <CheckOutlined />
                </a-button>
              </PermissionButton>

              <PermissionButton permission="circle:post:audit">
                <a-button
                  v-if="record.postStatus === 'pending'"
                  type="link"
                  size="small"
                  danger
                  @click="handleAudit(record, 'hidden')"
                  class="action-btn audit-btn"
                >
                  <CloseOutlined />
                </a-button>
              </PermissionButton>

              <PermissionButton permission="circle:post:pin">
                <a-button
                  v-if="record.isPinned === 0"
                  type="link"
                  size="small"
                  @click="handlePin(record)"
                  class="action-btn"
                >
                  <PushpinOutlined />
                </a-button>
              </PermissionButton>

              <PermissionButton permission="circle:post:delete">
                <a-popconfirm
                  title="确定要删除这个帖子吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handleDelete(record)"
                  placement="topRight"
                >
                  <a-button type="link" size="small" danger class="action-btn">
                    <DeleteOutlined />
                  </a-button>
                </a-popconfirm>
              </PermissionButton>
            </div>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 帖子详情弹窗 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="帖子详情"
      width="800px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div v-if="currentPost" class="post-detail">
        <div class="post-header">
          <h3>{{ currentPost.title }}</h3>
          <div class="post-meta">
            <a-tag :color="getStatusColor(currentPost.postStatus)">
              {{ getStatusText(currentPost.postStatus) }}
            </a-tag>
            <span class="meta-item">
              发布者：{{ currentPost.isAnonymous === 1 ? '匿名用户' : currentPost.userNickName }}
            </span>
            <span class="meta-item"> 发布时间：{{ formatDateTime(currentPost.createTime) }} </span>
          </div>
        </div>

        <div class="post-content">
          <div class="content-text">{{ currentPost.content }}</div>

          <!-- 话题标签 -->
          <div
            v-if="currentPost.postTagList && currentPost.postTagList.length > 0"
            class="post-tags"
          >
            <a-tag v-for="tag in currentPost.postTagList" :key="tag" color="blue">
              #{{ tag }}
            </a-tag>
          </div>

          <!-- 图片展示 -->
          <div
            v-if="currentPost.postImages && currentPost.postImages.length > 0"
            class="post-images"
          >
            <a-image-preview-group>
              <a-image
                v-for="(image, index) in currentPost.postImages"
                :key="index"
                :src="image"
                :width="120"
                :height="120"
                style="margin-right: 8px; margin-bottom: 8px; object-fit: cover"
              />
            </a-image-preview-group>
          </div>
        </div>

        <div class="post-stats">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-statistic title="浏览量" :value="currentPost.viewCount" />
            </a-col>
            <a-col :span="6">
              <a-statistic title="点赞数" :value="currentPost.likeCount" />
            </a-col>
            <a-col :span="6">
              <a-statistic title="评论数" :value="currentPost.commentCount" />
            </a-col>
            <a-col :span="6">
              <a-statistic title="分类" :value="currentPost.categoryName || '未分类'" />
            </a-col>
          </a-row>
        </div>
      </div>
    </a-modal>

    <!-- 置顶设置弹窗 -->
    <a-modal
      v-model:open="pinModalVisible"
      title="设置置顶"
      width="400px"
      @ok="handleConfirmPin"
      @cancel="handleCancelPin"
    >
      <a-form :model="pinForm" layout="vertical">
        <a-form-item label="置顶过期时间" required>
          <a-date-picker
            v-model:value="pinForm.pinExpireTime"
            show-time
            placeholder="请选择置顶过期时间"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  SearchOutlined,
  EyeOutlined,
  LikeOutlined,
  MessageOutlined,
  CheckOutlined,
  CloseOutlined,
  PushpinOutlined,
  PushpinFilled,
  DeleteOutlined,
  PlusOutlined,
  EditOutlined,
  EyeInvisibleOutlined,
  UserOutlined,
  BankOutlined,
  GlobalOutlined,
  FileTextOutlined,
  PlusCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import type { Post, PostPageParams, School, SchoolPageParams } from '@/types'
import { postService } from '@/api/post'
import { schoolService } from '@/api/school'
import PermissionButton from '@/components/PermissionButton.vue'
import { debounce } from '@/utils/debounce'

// 路由
const router = useRouter()

// 页面状态
const loading = ref(false)
const detailModalVisible = ref(false)
const pinModalVisible = ref(false)
const currentPost = ref<Post | null>(null)
const currentPinPost = ref<Post | null>(null)

// 图表引用
const publishTrendChart = ref<HTMLElement>()
const statusDistributionChart = ref<HTMLElement>()
const schoolRankChart = ref<HTMLElement>()
const interactionChart = ref<HTMLElement>()

// 统计数据（模拟数据）
const totalPosts = ref(2845)
const todayNewPosts = ref(127)
const pendingPosts = ref(23)
const totalViews = ref(458000)

// 搜索表单
const searchForm = reactive({
  title: '',
  postStatus: undefined as string | undefined,
  isPinned: undefined as number | undefined,
  schoolId: undefined as number | undefined,
})

// 学校列表
const schoolList = ref<School[]>([])

// 表格数据
const tableData = ref<Post[]>([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条数据`,
})

// 置顶表单
const pinForm = reactive({
  pinExpireTime: null as Dayjs | null,
})

// 格式化浏览量显示
const formatViewCount = (count: number) => {
  if (count >= 1000000) {
    return Math.floor(count / 1000000) + 'M'
  } else if (count >= 1000) {
    return Math.floor(count / 1000) + 'K'
  }
  return count.toString()
}

// 初始化图表
const initCharts = () => {
  setTimeout(() => {
    initPublishTrendChart()
    initStatusDistributionChart()
    initSchoolRankChart()
    initInteractionChart()
  }, 100)
}

// 帖子发布趋势图 - 改为堆叠柱状图
const initPublishTrendChart = () => {
  if (!publishTrendChart.value) return

  const chart = echarts.init(publishTrendChart.value)
  const dates = Array.from({ length: 7 }, (_, i) =>
    dayjs()
      .subtract(6 - i, 'day')
      .format('MM-DD')
  )
  const publishData = [45, 52, 61, 58, 67, 73, 84]
  const auditData = [12, 15, 18, 16, 19, 21, 23]

  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ccc',
      textStyle: { color: '#666' },
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      top: '5%',
      data: ['发布数量', '审核数量'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
      splitLine: { lineStyle: { color: '#f0f0f0' } },
    },
    series: [
      {
        name: '发布数量',
        type: 'bar',
        stack: 'total',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#1890ff' },
              { offset: 1, color: '#69c0ff' },
            ],
          },
          borderRadius: [4, 4, 0, 0],
        },
        data: publishData,
      },
      {
        name: '审核数量',
        type: 'bar',
        stack: 'total',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#fa8c16' },
              { offset: 1, color: '#ffd666' },
            ],
          },
        },
        data: auditData,
      },
    ],
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 帖子状态分布图 - 改为水平柱状图
const initStatusDistributionChart = () => {
  if (!statusDistributionChart.value) return

  const chart = echarts.init(statusDistributionChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ccc',
      textStyle: { color: '#666' },
      axisPointer: {
        type: 'shadow',
      },
      formatter: function (params: any) {
        const param = params[0]
        const total = 2845
        const percentage = ((param.value / total) * 100).toFixed(1)
        return `${param.name}<br/>${param.seriesName}: ${param.value} (${percentage}%)`
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '8%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
      splitLine: { lineStyle: { color: '#f0f0f0' } },
    },
    yAxis: {
      type: 'category',
      data: ['已隐藏', '审核中', '已发布'],
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
    },
    series: [
      {
        name: '帖子数量',
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          borderRadius: [0, 4, 4, 0],
        },
        data: [
          {
            value: 23,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [
                  { offset: 0, color: '#ff4d4f' },
                  { offset: 1, color: '#ff7875' },
                ],
              },
            },
          },
          {
            value: 274,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [
                  { offset: 0, color: '#fa8c16' },
                  { offset: 1, color: '#ffa940' },
                ],
              },
            },
          },
          {
            value: 2548,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [
                  { offset: 0, color: '#52c41a' },
                  { offset: 1, color: '#73d13d' },
                ],
              },
            },
          },
        ],
      },
    ],
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 学校发帖排行图
const initSchoolRankChart = () => {
  if (!schoolRankChart.value) return

  const chart = echarts.init(schoolRankChart.value)
  const schools = [
    '清华大学',
    '北京大学',
    '复旦大学',
    '上海交大',
    '浙江大学',
    '中科大',
    '南京大学',
    '武汉大学',
  ]
  const postCounts = [245, 213, 198, 187, 165, 152, 138, 124]

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
      splitLine: { lineStyle: { color: '#f0f0f0' } },
    },
    yAxis: {
      type: 'category',
      data: schools,
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
    },
    series: [
      {
        name: '发帖数量',
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#1890ff' },
              { offset: 1, color: '#69c0ff' },
            ],
          },
          borderRadius: [0, 4, 4, 0],
        },
        data: postCounts,
      },
    ],
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 互动数据概览图
const initInteractionChart = () => {
  if (!interactionChart.value) return

  const chart = echarts.init(interactionChart.value)
  const categories = ['本周', '上周', '上月']

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
    },
    legend: {
      top: '5%',
      data: ['浏览量', '点赞数', '评论数'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
      splitLine: { lineStyle: { color: '#f0f0f0' } },
    },
    series: [
      {
        name: '浏览量',
        type: 'bar',
        data: [12580, 15420, 18650],
        itemStyle: { color: '#1890ff' },
      },
      {
        name: '点赞数',
        type: 'bar',
        data: [2580, 3240, 3980],
        itemStyle: { color: '#52c41a' },
      },
      {
        name: '评论数',
        type: 'bar',
        data: [1580, 2140, 2650],
        itemStyle: { color: '#fa8c16' },
      },
    ],
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 60,
    fixed: 'left',
  },
  {
    title: '帖子标题',
    dataIndex: 'title',
    key: 'title',
    width: 200,
    ellipsis: true,
  },
  {
    title: '帖子内容',
    key: 'content',
    width: 250,
    slots: { customRender: 'content' },
  },
  {
    title: '发布者',
    key: 'publisher',
    width: 150,
    slots: { customRender: 'publisher' },
  },
  {
    title: '学校',
    key: 'school',
    width: 130,
    slots: { customRender: 'school' },
  },
  {
    title: '分类',
    dataIndex: 'categoryName',
    key: 'categoryName',
    width: 120,
    customRender: ({ text }: { text: string }) => text || '未分类',
  },
  {
    title: '状态',
    key: 'postStatus',
    width: 100,
    slots: { customRender: 'postStatus' },
  },
  {
    title: '置顶状态',
    key: 'pinStatus',
    width: 100,
    slots: { customRender: 'pinStatus' },
  },
  {
    title: '统计信息',
    key: 'stats',
    width: 130,
    slots: { customRender: 'stats' },
  },
  {
    title: '发布时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    customRender: ({ text }: { text: string }) => formatDateTime(text),
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    slots: { customRender: 'action' },
  },
]

// 获取状态颜色
const getStatusColor = (status: string) => {
  switch (status) {
    case 'published':
      return 'green'
    case 'pending':
      return 'orange'
    case 'hidden':
      return 'red'
    default:
      return 'default'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'published':
      return '已发布'
    case 'pending':
      return '审核中'
    case 'hidden':
      return '已隐藏'
    default:
      return '未知'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// 禁用过去的日期
const disabledDate = (current: Dayjs) => {
  return current && current < dayjs().endOf('day')
}

// 加载帖子列表数据
const fetchData = async () => {
  try {
    loading.value = true
    const params: PostPageParams = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    }

    const result = await postService.getPostPage(params)
    tableData.value = result.result
    pagination.total = result.total
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    message.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 加载学校列表
const loadSchoolList = async (schoolName = '') => {
  try {
    const params: SchoolPageParams = {
      page: 1,
      pageSize: 50,
      schoolName,
    }
    const result = await schoolService.getSchoolPage(params)
    schoolList.value = result.result
  } catch (error) {
    console.error('获取学校列表失败:', error)
  }
}

// 防抖搜索学校
const handleSchoolSearch = debounce((value: string) => {
  loadSchoolList(value)
}, 500)

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    postStatus: undefined,
    isPinned: undefined,
    schoolId: undefined,
  })
  pagination.current = 1
  fetchData()
}

// 表格分页变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchData()
}

// 查看详情
const handleViewDetail = async (record: Post) => {
  try {
    currentPost.value = await postService.getPostDetail(record.id)
    detailModalVisible.value = true
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    message.error('获取帖子详情失败')
  }
}

// 新增帖子 - 跳转到新增页面
const handleAdd = () => {
  router.push('/circles/post/add')
}

// 编辑帖子 - 跳转到编辑页面
const handleEdit = (record: Post) => {
  router.push(`/circles/post/edit/${record.id}`)
}

// 审核帖子
const handleAudit = async (record: Post, newStatus: string) => {
  try {
    await postService.updatePost({
      id: record.id,
      postStatus: newStatus,
    })
    message.success(`${newStatus === 'published' ? '审核通过' : '审核拒绝'}成功`)
    fetchData()
  } catch (error) {
    console.error('审核帖子失败:', error)
    message.error('审核帖子失败')
  }
}

// 置顶帖子
const handlePin = (record: Post) => {
  currentPinPost.value = record
  pinForm.pinExpireTime = null
  pinModalVisible.value = true
}

// 确认置顶
const handleConfirmPin = async () => {
  if (!pinForm.pinExpireTime) {
    message.error('请选择置顶过期时间')
    return
  }

  try {
    await postService.updatePost({
      id: currentPinPost.value!.id,
      isPinned: 1,
      pinExpireTime: pinForm.pinExpireTime.format('YYYY-MM-DD HH:mm:ss'),
    })
    message.success('置顶成功')
    pinModalVisible.value = false
    fetchData()
  } catch (error) {
    console.error('置顶帖子失败:', error)
    message.error('置顶帖子失败')
  }
}

// 取消置顶弹窗
const handleCancelPin = () => {
  pinModalVisible.value = false
  currentPinPost.value = null
  pinForm.pinExpireTime = null
}

// 取消置顶
const handleUnpin = async (record: Post) => {
  try {
    await postService.updatePost({
      id: record.id,
      isPinned: 0,
      pinExpireTime: '',
    })
    message.success('取消置顶成功')
    fetchData()
  } catch (error) {
    console.error('取消置顶失败:', error)
    message.error('取消置顶失败')
  }
}

// 删除帖子
const handleDelete = async (record: Post) => {
  try {
    await postService.deletePost(record.id)
    message.success('删除成功')
    fetchData()
  } catch (error) {
    console.error('删除帖子失败:', error)
    message.error('删除帖子失败')
  }
}

// 页面初始化
onMounted(() => {
  fetchData()
  loadSchoolList()
  initCharts()
})
</script>

<style scoped lang="scss">
.page-container {
  padding: 24px;
}

.stats-cards {
  margin-bottom: 24px;

  .stat-card {
    border-radius: 8px;
    overflow: hidden;

    :deep(.ant-card-body) {
      padding: 20px;
    }
  }

  .stat-content {
    position: relative;

    .stat-number {
      font-size: 28px;
      font-weight: bold;
      color: #1d1d1f;
      line-height: 1;
      margin-bottom: 8px;
    }

    .stat-label {
      font-size: 14px;
      color: #666;
    }

    .stat-icon {
      position: absolute;
      top: 0;
      right: 0;
      width: 48px;
      height: 48px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: white;

      &.total {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.today {
        background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
        color: #d46b08;
      }

      &.pending {
        background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
        color: #d4380d;
      }

      &.views {
        background: linear-gradient(135deg, #a8e6cf 0%, #88d8a3 100%);
        color: #389e0d;
      }
    }
  }
}

.charts-section {
  margin-bottom: 24px;

  .chart-card {
    border-radius: 8px;
    overflow: hidden;

    :deep(.ant-card-head) {
      border-bottom: 1px solid #f0f0f0;
    }
  }

  .chart-container {
    height: 280px;
    width: 100%;
  }
}

.search-form {
  margin-bottom: 24px;
  padding: 24px 24px 16px 24px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;

  .ant-form {
    .ant-form-item {
      margin-bottom: 16px;
      margin-right: 24px;

      &:last-child {
        margin-right: 0;
        margin-bottom: 0;
      }

      .ant-form-item-label {
        font-weight: 500;
        color: #333;

        > label {
          font-size: 14px;
        }
      }

      .ant-form-item-control {
        .ant-input,
        .ant-select .ant-select-selector {
          border-radius: 6px;
          border: 1px solid #d9d9d9;
          transition: all 0.3s ease;

          &:hover {
            border-color: #40a9ff;
          }

          &:focus,
          &.ant-select-focused .ant-select-selector {
            border-color: #1890ff;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
          }
        }

        .ant-btn {
          border-radius: 6px;
          font-weight: 500;
          height: 32px;
          padding: 4px 15px;

          &.ant-btn-primary {
            background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
            border: none;
            box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);

            &:hover {
              background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
              box-shadow: 0 4px 8px rgba(24, 144, 255, 0.4);
              transform: translateY(-1px);
            }
          }

          &:not(.ant-btn-primary) {
            border: 1px solid #d9d9d9;
            background: #fff;

            &:hover {
              border-color: #40a9ff;
              color: #40a9ff;
            }
          }
        }
      }
    }
  }
}

.content-preview {
  line-height: 1.5;
  color: #666;
}

.publisher-info {
  .publisher-name {
    font-weight: 500;
    margin-bottom: 4px;
    color: #1d1d1f;
  }

  .publisher-meta {
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

.school-info {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8px;
}

.pin-status {
  .pin-expire {
    margin-top: 4px;
    color: #999;
    font-size: 12px;
  }
}

.pin-detail {
  min-width: 200px;

  p {
    margin-bottom: 8px;
    line-height: 1.5;
  }
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 2px;
  justify-content: flex-start;
  align-items: center;
  max-width: 180px;

  .action-btn {
    padding: 0 4px;
    height: 24px;
    line-height: 22px;
    min-width: 24px;

    .anticon {
      font-size: 12px;
    }
  }

  .audit-btn {
    margin: 0 1px;
  }
}

.stats-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;

  .stat-item {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #666;

    .anticon {
      color: #1890ff;
    }
  }
}

.text-muted {
  color: #999;
  font-size: 12px;
}

.post-detail {
  .post-header {
    margin-bottom: 24px;

    h3 {
      margin-bottom: 12px;
      font-size: 18px;
      font-weight: 600;
    }

    .post-meta {
      display: flex;
      align-items: center;
      gap: 16px;

      .meta-item {
        color: #666;
        font-size: 14px;
      }
    }
  }

  .post-content {
    margin-bottom: 24px;

    .content-text {
      margin-bottom: 16px;
      line-height: 1.6;
      white-space: pre-wrap;
    }

    .post-tags {
      margin-bottom: 16px;
    }

    .post-images {
      :deep(.ant-image) {
        border-radius: 6px;
        overflow: hidden;
      }
    }
  }

  .post-stats {
    padding: 16px 0;
    border-top: 1px solid #f0f0f0;
  }
}
</style>